﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using System.Net;
using ZUtil;
namespace EEGServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private delegate void DG();
        private TcpClient client_tr = null;
        private double[] vals = new double[8];

        private void step_useSave()
        {
            status = 1;
            DG dg = delegate ()
            {
                label_status.Text = "用户保存(0xA1)";
            };
            Invoke(dg);

            addMsg("用户保存(0xA1)");
        }

        private void step1()
        {
            status = 2;
            DG dg = delegate ()
            {
                label_status.Text = "第一步(0xA2)";
            };
            Invoke(dg);
            addMsg("第一步");

        }
        private void step2()
        {
            status = 3;
            DG dg = delegate ()
            {
                label_status.Text = "第二步(A3)";
            };
            Invoke(dg);
            addMsg("第二步");

        }
        private void step_start()
        {
            addMsg("开始采集发送");
            collTime = DateTime.Now;
            lock (dataItemList)
            {
                dataItemList.Clear();
            }
            status = 4;
        }
        
        private void step0()
        {
            status = 0;
            DG dg = delegate ()
            {
                label_status.Text = "未连接";
            };
            Invoke(dg);
        }
      
        private DateTime collTime = DateTime.MinValue;
        private int status = 0;
        Queue<byte[]> dataItemList = new Queue<byte[]>();
        private void Form1_Load(object sender, EventArgs e)
        {
            #region 模拟数据
            for (var i = 0; i < vals.Length; i++)
            {
                Label label = new Label();
                label.Location = new Point(10, 25 * (i + 1));
                label.AutoSize = true;
                groupBox1.Controls.Add(label);
            }
            new Thread(delegate ()
            {

                while (true)
                {
                    for (var i = 0; i < vals.Length; i++)
                    {

                        //long s = DateTime.Now.Ticks / 1000;
                        long s = DateTime.Now.Ticks / 10000 / 10 + i * 20;

                        double a = Math.Sin(s / 20.0 * Math.PI) * 30;
                        vals[i] = a + 200;

                        switch (i)
                        {
                            case 0:
                                vals[i] += 120;
                                break;
                            case 1:
                                vals[i] += 50;
                                break;
                            case 2:
                                break;
                            case 3:
                                vals[i] -= 100;
                                break;
                            case 4:
                                vals[i] -= 50;
                                break;
                        }

                        DG dg = delegate ()
                        {
                            String str = "线路" + (i + 1) + ":" + vals[i];
                            groupBox1.Controls[i].Text = str;
                        };
                        Invoke(dg);
                    }

                  
                    Thread.Sleep(10);
                }

            }).Start();
            #endregion 模拟数据


            #region 模拟采集数据
            new Thread(delegate ()
            {
                while (true)
                {
                    if (status != 4)
                    {
                        continue;
                    }
                    byte[] bs = new byte[320];
                    for (var i = 0; i < 10; i++)
                    {
                        long dt = (DateTime.Now - collTime).Ticks / 10000;
                        BitConverter.GetBytes((int)dt).CopyTo(bs, i * 32);//时间部分
                        new byte[] { 0, 0xC, 0, 0 }.CopyTo(bs, i * 32 + 4);//标志位
                        for (var j = 0; j < vals.Length; j++)
                        {
                            var data = new byte[3] { 111, 111, 111 };
                            data.CopyTo(bs, i * 32 + 4+4 + j * 3);
                        }
                        Thread.Sleep(10);
                    }
                    //此处可能造成时间损失...
                    lock (dataItemList)
                    {
                        dataItemList.Enqueue(bs);
                    }
                    bs = new byte[320];

                }

            }).Start();

            #endregion 模拟采集数据


            #region 模拟发送数据
            new Thread(delegate ()
            {
                while (true)
                {
                    if (status != 4)
                    {
                        continue;
                    }

                    try
                    {
                        byte[] rbs = null;

                        lock (dataItemList)
                        {
                            rbs = dataItemList.Dequeue();
                        }
                        if (rbs.Length > 0)
                        {
                            client_tr.Client.Send(rbs);
                        }
                        Thread.Sleep(10);
                    }
                    catch (Exception ex)
                    {
                        if (client_tr != null && !client_tr.Connected)
                        {
                            step0();
                        }

                    }

                }

            }).Start();
            #endregion 模拟发送数据



            TcpListener listener4308 = new TcpListener(4308);//指令控制端口
            listener4308.Start();
            TcpListener listener4309 = new TcpListener(4309);//数据端口
            listener4309.Start();
            
            addMsg("开启指令监听:4309,数据端口");
            addMsg("开启数据监听:4308,指令控制端口");


            //线程处理4309端口(数据传输端口)
            new Thread(delegate ()
            {
                client_tr = listener4309.AcceptTcpClient();
                client_tr.Client.Send(new byte[] { 0xBB, 0x00, 0x00, 0x00 });
            }).Start();

            //线程处理4308端口(指令端口)
            new Thread(delegate ()
            {

            try
            {
                while (true)
                {
                    var clientOrder = listener4308.AcceptTcpClient();
                    clientOrder.Client.Send(new byte[] { 0xBB });
                        addMsg("指令端口有新连接进入");
                        addMsg("指令端口回复:0xBB");


                        #region 处理接收命令
                        while (clientOrder.Connected)
                        {
                            try
                            {
                                byte[] bs = new byte[1024];
                                int len = clientOrder.Client.Receive(bs);
                                if (len == 0)
                                {
                                    //连接被关闭了
                                    addMsg("连接被关闭了");
                                    break;
                                }

                                String recStr = ByteUtil.byteToString(bs, len).Trim();
                                switch (recStr)
                                {
                                    case "A1":
                                        step_useSave();
                                        clientOrder.Client.Send(new byte[] { 0xBB,0xB1,0,0});
                                        addMsg("发送0xBB B1 00 00");
                                        break;
                                    case "A2":
                                        step1();
                                        clientOrder.Client.Send(new byte[] {0xBB,0xB1,0xB2,0 });
                                        addMsg("发送0xBB B1 B2 00");
                                        break;
                                    case "A3":
                                        step2();
                                        clientOrder.Client.Send(new byte[] { 0xBB,0xB1,0xB2,0xB3 });
                                        break;
                                    case "AA":
                                        clientOrder.Client.Send(new byte[] { 0xB4,0xB1,0xB2,0xB3 });
                                        step_start();
                                        break;
                                    case "EE":
                                        status = 5;
                                        clientOrder.Client.Send(new byte[] { 0xBB,0,0,0 });
                                        break;
                                    default:
                                        addMsg("未知命令:" + recStr);
                                        break;
                                }
                            }
                            catch (Exception ex)
                            {
                                addMsg("处理接收命令出错:" + ex.Message);
                            }

                        }
                        #endregion 处理接收命令

                    }
                }
                catch (Exception ex)
                {
                    addMsg("出错了:" + ex.Message);
                }



            }).Start();




        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }
        private void addMsg(String txt)
        {
            DG dg = delegate ()
            {
                textBox1.AppendText(txt + "\r\n");
            };
            Invoke(dg);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
